<template>
  <div class="user-center-container">
    <h2 class="title">个人中心</h2>
    <div class="user-info">
      <p><strong>用户名：</strong>{{ userInfo.name }}</p>
      <p><strong>邮箱：</strong>{{ userInfo.email }}</p>
      <p><strong>注册时间：</strong>{{ userInfo.registerDate }}</p>
    </div>

    <!-- 仅管理员可见的管理后台入口按钮 -->
    <div class="admin-entry" v-if="isAdmin">
      <el-button type="primary" @click="goAdmin">进入管理员后台</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
// 简单的个人中心数据
import { useUserStore } from '@/stores/auth/user';
import { storeToRefs } from 'pinia'
import { computed,watch } from 'vue';
import { useRouter } from 'vue-router'
const userStore = useUserStore()
const { user, token } = storeToRefs(userStore)
const router = useRouter()

const userInfo = computed(() => ({
  name: user.value.username || '—',
  email: user.value.email || '—',
  registerDate: user.value.created_at
    ? new Date(user.value.created_at).toLocaleString()
    : '—'
}))

// 仅管理员显示按钮
const isAdmin = computed(() => userStore.isAdmin)

function goAdmin() {
  router.push({ path: '/admin-dashboard' })
}

watch(
  token,(t)=>{
    if (t && (!user.value?.id || !user.value.username)) {
      userStore.fetchUserInfo().catch(console.error)
    }
  },{immediate:true}
)

</script>

<style scoped>
.user-center-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  margin-top: 70px; /* 使用外边距替代内边距，确保完全避开导航栏 */
}
.title {
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 20px;
}
.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 8px;
}
</style>